var API = require('wechat-enterprise').API;

module.exports = (function(){
		
	//Wechat Api
	var wxapi = null;
	
	var weserv = {
			
		init : function (){
			
			var config = sails.config.connections.weixinServer;
			wxapi = new API(config.corpid, config.secret, config.agentid);
			
		},
		
		getAuthorizeURL : function(){
			return wxapi.getAuthorizeURL(sails.config.application.appPath + '/login', '', 'snsapi_base');
		},
		
		getJsApiTicket : function(cb){
			wxapi.getTicket(cb);
		},
		
		downloadFile : function(media,cb){
			wxapi.getMedia(media, cb);
		},
		
		getUserByCode : function(code, cb){
			
			wxapi.getUserIdByCode(code, function(err, result){
				if(!err){
					User.findOne(result.UserId)
					.then(function (result) {
						sails.log.info('get user [' + result.userid + '] by code.');
						cb(err, result);
					}).catch(function(err){
						sails.log.error(err);
					});
				}else{
					cb(err, result);
				}
			});
			
		},
		
		/*sendMessage : function(to, message, callback){
			
			wxapi.send(to, message, callback)
			
		},*/
		
		sendNewsMessage : function(userid, url, title, description, cb){
			
			var to = {
				"touser": userid
			};
			
			sails.log.info("Send to user [" + userid +"] :" + url);
			
			var message = {
				"msgtype": "news",
				"news": {
					"articles":[{
						"title": title,
						"description": description,
						"url": url,
						"picurl": "",
					}]
				 },
				 "safe":"0"
			};
			
			wxapi.send(to, message, cb);
			
		},
	
		sendFormToChecker : function(form, url, req, cb){
			
			if(form.type == sails.config.application.sysform.note){
				url += "#!" + sails.config.application.appPrefix + "/note/get?method=detail&pkid=" + form.note;
			}else {
				url += "#!" + sails.config.application.appPrefix + "/form/get?method=detail&pkid=" + form.id;
			}

			User.findOne(form.owner)
			.then(function findOneCB(owner){
				
				weserv.sendNewsMessage(form.waitChecker, url, "您有一个报表需要审批", form.name + " [" + owner.name + "]" , cb);
				
			}).catch(function(err){
				sails.log.error(err);
			});
			
		},
		
		sendFormToOwner : function(form, url, req, cb){
			
			if(form.type == sails.config.application.sysform.note){
				url += "#!" + sails.config.application.appPrefix + "/note/get?method=detail&pkid=" + form.note;
			}else {
				url += "#!" + sails.config.application.appPrefix + "/form/get?method=detail&pkid=" + form.id;
			}
			
			User.findOne(form.lastChecker)
			.then(function findOneCB(lastChecker){
				
				weserv.sendNewsMessage(form.owner, url, "您有一个报表已经审批完成", form.name + " [" + lastChecker.name + "]" , cb);
				
			}).catch(function(err){
				sails.log.error(err);
			});
			
		},
		
		syncUser : function(cb){
			
			wxapi.getDepartmentUsersDetail(1, 1, 0, function(err, result) {
				if (!err && result.errcode == 0) {
					User.destroy({})
					.then(function () {
						User.create(result.userlist)
						.then(function (result) {
							sails.log.info('Sync wechat users successfully.');
							cb(result);
						});
					}).catch(function(err){
						sails.log.error(err);
					});
					
				} else {
					sails.log.error(err);
				}
			});
			
		},
		
		syncData : function(){
			weserv.syncUser(function(users){
				weserv.syncDepartment(users);
			});
		},
		
		syncDepartment : function(users){
			
			wxapi.getDepartments(function(err, result) {
				if (!err && result.errcode == 0) {
					Department.destroy({})
					.then(function () {
						
						var deptMap = {};
						for (var i = 0; i < users.length; i++) {
							var depts = users[i].department;
							if(depts != undefined){
								for (var j = 0; j < depts.length; j++) {
									if(deptMap[depts[j]] == undefined){
										deptMap[depts[j]] = [];
									}
									deptMap[depts[j]].push(users[i].userid);
								}
							}
						}
						
						for (var i = 0; i < result.department.length; i++) {
							result.department[i].userlist = deptMap[result.department[i].id]
						}
						
						Department.create(result.department)
						.then(function (result) {
							sails.log.info('Sync wechat departments successfully.');
						});
						
					}).catch(function(err){
						sails.log.error(err);
					});
					
				} else {
					sails.log.error(err);
				}
			});
		},
		
	};
	
	weserv.init();
	
	return weserv;
	
	/*accessToken : null,
	_httpClient : null,
	_this : null,
	_getAccessToken : function (){
		
		this._httpClient.post('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='+ sails.config.weixin.corpid + '&corpsecret=' + sails.config.weixin.secret)
		.end(function(response) {
			if (response.body.access_token) {
				_this.accessToken = response.body.access_token;
				sails.log.info('Get weixin token:' + _this.accessToken);
			} else {
				sails.log.error('Get weixin token error.[code:'+ response.body.errcode + ']');
			}
		});
	},
	init : function (){
		_this = this;
		this._httpClient = require('unirest');
		this._getAccessToken();
		setInterval(this._getAccessToken, 7100*1000);
	},*/
	
})();